<?php

function get_db(){
    return lib_mysql::getInstance(lib_config::$db);
}

class lib_mysql {

    private $link;

    public static $_instance = array();

    public static function getInstance($option){
        $opt = ksort($option);
        $key = md5(var_export($opt, true));
        if(!isset(self::$_instance[$key])){
            self::$_instance[$key] = new lib_mysql($option);
        }
        return self::$_instance[$key];
    }

    public function __construct($option){

        $this->connect($option["host"], 
            $option["username"], 
            $option["password"], 
            $option["dbname"], 
            $option["charset"]); 

    }

    public function connect($host, $username, $password, $dbname = "", $charset = ""){
        if(!$this->link = mysql_connect($host, $username, $password)) {
            $this->halt('Can not connect to MySQL server: '. $username . "@" . $host , @mysql_error());
            exit;
        }

        if(!empty($charset)){
            mysql_unbuffered_query("SET NAMES " . $charset, $this->link);
        }

        if(!empty($dbname)){
            $this->select_db($dbname);
        }

    }

    public function close(){
        if(is_resource($this->link)){
            mysql_close($this->link);
        }
    }

    public function select_db($dbname) {
        return mysql_select_db($dbname, $this->link);
    }

    public function query($sql){
        $rs = @mysql_unbuffered_query($sql, $this->link);
        if($rs === false){
            $this->halt(mysql_error($this->link), $sql);
        }
        return $rs;
    }

    public function query_buffered($sql){
        $rs = @mysql_query($sql, $this->link);
        if($rs === false){
            $this->halt(mysql_error($this->link), $sql);
        }
        return $rs;
    }

    public function fetch($query, $result_type = MYSQL_ASSOC) {
        return @mysql_fetch_array($query, $result_type);
    }

    public function query_fetch($sql){
        $rs = $this->query($sql);
        if($rs !== false){
            return $this->fetch($rs);
        } else {
            return false;
        }
    }

    public function insert_id(){
        $rs = $this->query("SELECT last_insert_id() AS LAST_ID");
        $row = $this->fetch($rs);
        return $row["LAST_ID"];
    }

    public function affected_rows(){
        return mysql_affected_rows($this->link);
    }

    public function escape($str){
        return mysql_real_escape_string($str, $this->link);
    }


    public function halt($message = '', $sql = '') {
        error_log($message . "|" . $sql);
        @ ob_clean();
        echo "<p>Database Error.<br />Please check the error log.</p>";
        exit;
    }


}


